home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 5 / Apprentice-Release5.iso / Source Code / Libraries / LinAlg 3.1 / LinAlg / vzeroin.cc < prev    next >
Encoding:
C/C++ Source or Header  |  1995-12-21  |  1.1 KB  |  54 lines  |  [TEXT/ttxt]

  1. // This may look like C code, but it is really -*- C++ -*-
  2. //
  3. //            Verify ZEROIN routine
  4.  
  5. #include "math_num.h"
  6. #include <iostream.h>
  7.  
  8. static int counter;            // Iteration counter
  9.  
  10.             // Run a test
  11. static void test
  12.   (const double a, const double b, double (*f)(double x), const char *msg)
  13. {
  14.   double root;
  15.   counter = 0;
  16.   printf("\nFor function %s,\nthe root over [%g,%g] is\t%.9e\n",msg,a,b,
  17.      (root=zeroin(a,b,f)) );
  18.   printf("Function value at the root found\t%.4e\n"
  19.            "No. of iterations\t\t%d\n",
  20.            (*f)(root), counter);
  21. }
  22.  
  23. static double f1(const double x)        // Test from the Forsythe book
  24. {
  25.   counter++;
  26.   return (sqr(x)-2)*x - 5;
  27. }
  28.  
  29. static double f2(const double x)
  30. {
  31.   counter++;
  32.   return cos(x) - x;
  33. }
  34.  
  35. static double f3(const double x)
  36. {
  37.   counter++;
  38.   return sin(x) - x;
  39. }
  40.  
  41.  
  42. main(void)
  43. {
  44.   cout << "\n\n" << _Minuses <<
  45.           "\n\t\tTesting the Brent's root finder\n\n";
  46.  
  47.   test(2.0,3.0,f1,"x^3 - 2*x - 5");
  48.   cout << "Exact root is \t\t2.0945514815\n";
  49.  
  50.   test(2.0,3.0,f2,"cos(x)-x");
  51.   test(-1.0,3.0,f2,"cos(x)-x");
  52.   test(-1.0,3.0,f3,"sin(x)-x");
  53. }
  54.